/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.app;

import com.railway.reports.CashReconciliationCustomizer;
import com.railway.reports.CashReconciliationReport;
import com.railway.reports.MemberCustomizer;
import com.railway.reports.MemberReport;
import com.railway.reports.RedemptionCustomizer;
import com.railway.reports.RedemptionReport;
import com.railway.reports.SalesCustomizer;
import com.railway.reports.SalesReport;
import com.railway.reports.ScheduleCustomizer;
import com.railway.reports.ScheduleReport;
import com.railway.reports.TicketCustomizer;
import com.railway.reports.TicketReport;
import com.railway.utils.RestServer;
import com.railway.utils.Toast;
import java.awt.CardLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JFrame;
import net.sf.jasperreports.swing.JRViewer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Kenny
 */
public class ReportForm extends javax.swing.JPanel {

    private TicketCustomizer tcCustom;
    private ScheduleCustomizer scCustom;
    private RedemptionCustomizer rcCustom;
    private SalesCustomizer slcCustom;
    private MemberCustomizer mcCustom;
    private CashReconciliationCustomizer crCustom;
    private int choice = 0;
    private CardLayout cl, cl2;
    private TicketReport tr = new TicketReport();
    private ScheduleReport sr = new ScheduleReport();
    private RedemptionReport rr = new RedemptionReport();
    private SalesReport slr = new SalesReport();
    private MemberReport mr = new MemberReport();
    private CashReconciliationReport cr = new CashReconciliationReport();
    private JRViewer reportViewer;

    /**
     * Creates new form ReportPanel
     */
    public ReportForm() {
        initComponents();
        cl = (CardLayout) jPanel3.getLayout();
        cl2 = (CardLayout) jpReportView.getLayout();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jpNull = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jpReportView = new javax.swing.JPanel();

        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Report", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Emoji", 0, 12))); // NOI18N
        setPreferredSize(new java.awt.Dimension(890, 548));
        setLayout(null);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jPanel1.setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("<html>Please select the report you <br/>wanted to generate :");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(5, 10, 210, 40);

        jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Please make selection", "Ticket Report", "Schedule Report", "Redeem Report", "Sales Report", "Member Report", "Cash Reconciliation" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        jPanel1.add(jComboBox1);
        jComboBox1.setBounds(5, 60, 210, 30);

        jPanel3.setLayout(new java.awt.CardLayout());

        jpNull.setBackground(new java.awt.Color(255, 255, 255));
        jpNull.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpNull.setLayout(null);
        jPanel3.add(jpNull, "null");

        jPanel1.add(jPanel3);
        jPanel3.setBounds(5, 100, 210, 340);

        jButton1.setFont(new java.awt.Font("Segoe UI Emoji", 0, 24)); // NOI18N
        jButton1.setText("Generate !");
        jButton1.setFocusPainted(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(5, 450, 210, 80);

        add(jPanel1);
        jPanel1.setBounds(5, 15, 220, 530);

        jpReportView.setBackground(new java.awt.Color(255, 255, 255));
        jpReportView.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpReportView.setLayout(new java.awt.CardLayout());
        add(jpReportView);
        jpReportView.setBounds(230, 15, 650, 525);
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        choice = jComboBox1.getSelectedIndex();
        displayCustomizer(choice);
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jComboBox1.getSelectedIndex() > 0) {
            obtainReportData();
        } else {
            Toast.makeText(this, "Select report from the drop down list first.", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void displayCustomizer(int selection) {
        switch (selection) {
            case 1:
                tcCustom = new TicketCustomizer();
                jPanel3.add(tcCustom, "customizeticket");
                cl.show(jPanel3, "customizeticket");
                break;
            case 2:
                scCustom = new ScheduleCustomizer();
                jPanel3.add(scCustom, "customizeschedule");
                cl.show(jPanel3, "customizeschedule");
                break;
            case 3:
                rcCustom = new RedemptionCustomizer();
                jPanel3.add(rcCustom, "customizeredeem");
                cl.show(jPanel3, "customizeredeem");
                break;
            case 4:
                slcCustom = new SalesCustomizer();
                jPanel3.add(slcCustom, "customizersales");
                cl.show(jPanel3, "customizersales");
                break;
            case 5:
                mcCustom = new MemberCustomizer();
                jPanel3.add(mcCustom, "customizermember");
                cl.show(jPanel3, "customizermember");
                break;
            case 6:
                crCustom = new CashReconciliationCustomizer();
                jPanel3.add(crCustom, "customizercash");
                cl.show(jPanel3, "customizercash");
                break;
        }
    }

    private void obtainReportData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result;
                Map<String, Object> data;
                ArrayList<Map<String, Object>> dataList;
                switch (choice) {
                    case 1:
                        data = new HashMap<>();
                        data.put("query", tcCustom.buildQuery());
                        result = RestServer.httpPost("reporting", data);
                        dataList = jsonMapping(result);
                        if (!dataList.isEmpty()) {
                            tr.buildData(dataList);
                            reportViewer = tr.buildReport();
                            jpReportView.add(reportViewer, "ticket");
                            cl2.show(jpReportView, "ticket");
                        } else {
                            Toast.makeText(ReportForm.this, "No data found, please refine your criteria.", Toast.LENGTH_SHORT).display();
                        }
                        break;
                    case 2:
                        data = new HashMap<>();
                        data.put("query", scCustom.buildQuery());
                        result = RestServer.httpPost("reporting", data);
                        dataList = jsonMapping(result);
                        if (!dataList.isEmpty()) {
                            boolean isSummary = scCustom.isSummaryReport();
                            sr.buildData(dataList);
                            if (isSummary) {
                                reportViewer = sr.buildSummary();
                            } else {
                                reportViewer = sr.buildException();
                            }
                            jpReportView.add(reportViewer, "schedule");
                            cl2.show(jpReportView, "schedule");
                        } else {
                            Toast.makeText(ReportForm.this, "No data found, please refine your criteria.", Toast.LENGTH_SHORT).display();
                        }
                        break;
                    case 3:
                        data = new HashMap<>();
                        data.put("query", rcCustom.buildQuery());
                        result = RestServer.httpPost("reporting", data);
                        dataList = jsonMapping(result);
                        if (!dataList.isEmpty()) {
                            boolean isSummary = rcCustom.isSummaryReport();
                            rr.buildData(dataList);
                            if (isSummary) {
                                reportViewer = rr.buildSummary();
                            } else {
                                reportViewer = rr.buildException();
                            }
                            jpReportView.add(reportViewer, "redeem");
                            cl2.show(jpReportView, "redeem");
                        } else {
                            Toast.makeText(ReportForm.this, "No data found, please refine your criteria.", Toast.LENGTH_SHORT).display();
                        }
                        break;
                    case 4:
                        data = new HashMap<>();
                        data.put("query", slcCustom.buildQuery());
                        result = RestServer.httpPost("reporting", data);
                        dataList = jsonMapping(result);
                        if (!dataList.isEmpty()) {
                            slr.buildData(dataList);
                            reportViewer = slr.buildReport();
                            jpReportView.add(reportViewer, "sales");
                            cl2.show(jpReportView, "sales");
                        } else {
                            Toast.makeText(ReportForm.this, "No data found, please refine your criteria.", Toast.LENGTH_SHORT).display();
                        }
                        break;
                    case 5:
                        data = new HashMap<>();
                        data.put("query", mcCustom.buildQuery());
                        result = RestServer.httpPost("reporting", data);
                        dataList = jsonMapping(result);
                        for (int i = 0; i < dataList.size(); i++) {
                            Map<String, Object> map = dataList.get(i);
                            for (Map.Entry<String, Object> entry : map.entrySet()) {
                                String string = entry.getKey();
                                Object object = entry.getValue();
                                System.out.println(object);
                            }
                        }
                    case 6:
                        data = new HashMap<>();
                        data.put("query", crCustom.buildQuery());
                        result = RestServer.httpPost("reporting", data);
                        dataList = jsonMapping(result);
                        if (!dataList.isEmpty()) {
                            cr.buildData(dataList);
                            reportViewer = cr.buildReport();
                            jpReportView.add(reportViewer, "cash");
                            cl2.show(jpReportView, "cash");
                        } else {
                            Toast.makeText(ReportForm.this, "No data found, please refine your criteria.", Toast.LENGTH_SHORT).display();
                        }
                        break;
                }
            }
        }).start();

    }

    private ArrayList<Map<String, Object>> jsonMapping(String data) {
        Map<String, Object> temp;
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        try {
            JSONObject json = new JSONObject(data);
            boolean error = json.optBoolean("error");
            if (!error) {
                int statuscode = json.getInt("status");
                if (statuscode == 200) {
                    JSONArray jsonArr = json.getJSONArray("content");
                    for (int i = 0; i < jsonArr.length(); i++) {
                        Iterator<String> names = jsonArr.getJSONObject(i).keys();
                        temp = new HashMap<>();
                        while (names.hasNext()) {
                            String name = names.next();
                            temp.put(name, jsonArr.getJSONObject(i).get(name));
                        }
                        dataList.add(temp);
                    }
                }
            }
        } catch (JSONException ex) {
        }
        return dataList;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new ReportForm());
        frame.setVisible(true);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jpNull;
    private javax.swing.JPanel jpReportView;
    // End of variables declaration//GEN-END:variables
}
